#include <QMessageBox>
#include <QtSql>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "defaultsettings.h"
#include "settingsdialog.h"
#include "mixerwidget.h"
#include "chooserwidget.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    if (!openSqlDB())
    {
        QMessageBox::information(this, tr("Cannot open database"), tr("The angolmix.db3 file could not be opened.\nApplication closed."));
        exit(1);
    }
    ui->setupUi(this);
    int dbfileVersion = checkDatabase();
    if (dbfileVersion == CURRENT_DB_VERSION)
        statusBar()->showMessage("SQL connection Ok.", 10000);
    else
    {
        //create new empty tables;
        createDBTables(dbfileVersion);
        statusBar()->showMessage("SQL tables newly created or upgraded!", 10000);
    }
    ui->label_Version->setText(APP_VERSION);
    settingsLoad();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_actionAbout_Qt_triggered()
{
    qApp->aboutQt();
}

void MainWindow::on_actionAbout_AngolMix_triggered()
{
    QString abouttext(tr("This is a free, open-source English learning program, developed in Qt.") + "<br>");
    abouttext.append(tr("The GPL license under the terms of use.") + "<br><br>");
    abouttext.append(tr("Version number:") + " <b>" + APP_VERSION + "</b><br><hr>");
    abouttext.append(tr("Author: Gyula Blanka") + " <address>&lt;gyula@bsth.hu&gt;</address><br>");
    abouttext.append("<b>http://angolmix.googlecode.com</b>");
    QMessageBox::about(this, tr("About AngolMix"), abouttext);
}

void MainWindow::on_action_Settings_triggered()
{
    SettingsDialog dialog(this, &translator);
    int ret = dialog.exec();
    if (ret == QDialog::Accepted) {
        dialog.saveSettings();
        settingsLoad();
        emit settingsChangedSignal();
    }
}

void MainWindow::settingsLoad()
{
    settingsListMain.clear();
    DefaultSettings def;
    settingsListMain = def.getDefaultSettings("MAIN");
    int numberofsettings = settingsListMain.count();
    QSqlQuery query("SELECT * from settings WHERE Pref_Category=\"MAIN\"");
    while (query.next()) {
        QStringList settingfromDB;
        settingfromDB << query.record().value("Pref_Category").toString()
                   << query.record().value("Pref_Key").toString()
                   << query.record().value("Pref_Value").toString();
        for (int i = 0; i < numberofsettings; ++i) {
            if (settingsListMain.at(i).at(1) == settingfromDB.at(1)) {
                settingsListMain[i][2] = settingfromDB.at(2);
                break;
            }
        }
    }
    foreach (QStringList onesetting, settingsListMain) {
        if (onesetting.at(1) == "GUI_Language") {
            QString language(":/translations/");
            language.append(onesetting.at(2));
            translator.load(language);
            qApp->installTranslator(&translator);
            ui->retranslateUi(this);
        }
        else if (onesetting.at(1) == "GUI_Stylesheet") {
            QFile qss("stylesheets/style_" + onesetting.at(2) + ".qss");
            if (!qss.open(QIODevice::ReadOnly | QIODevice::Text)) {
                qss.setFileName(":/stylesheets/style_" + onesetting.at(2) + ".qss");
                qss.open(QIODevice::ReadOnly | QIODevice::Text);
            }
            qApp->setStyleSheet(qss.readAll());
            qss.close();
        }
    }
}

bool MainWindow::openSqlDB()
{
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("angolmix.db3");
    return db.open();
}

int MainWindow::checkDatabase()
{
    QSqlQuery query("SELECT * FROM version");
    query.next();
    int version = query.record().value("v").toInt();
    return version;
}

void MainWindow::createDBTables(int dbfileVersion)
{
    while (dbfileVersion < CURRENT_DB_VERSION) {
        ++dbfileVersion;
        QString sqlfilename = QString(":/sql/db_v%1.sql").arg(dbfileVersion);
        QFile sqlfile(sqlfilename);
        sqlfile.open(QFile::ReadOnly | QFile::Text);
        QString filecontent(sqlfile.readAll());
        sqlfile.close();
        QStringList commands(filecontent.split(";"));
        int count = commands.count();
        for (int i = 0; i < count; ++i)
            QSqlQuery query(commands.at(i));
    }
}

void MainWindow::on_commandLinkButton_Mixer_clicked()
{
    MixerWidget *mixerwidget = new MixerWidget(this);
    int stackerPageNumber = ui->stackedWidgetMain->addWidget(mixerwidget);
    ui->stackedWidgetMain->setCurrentIndex(stackerPageNumber);
    connect(this, SIGNAL(settingsChangedSignal()), mixerwidget, SLOT(settingsReloadFromMainSlot()));
}

void MainWindow::on_commandLinkButton_Chooser_clicked()
{
    ChooserWidget *chooserwidget = new ChooserWidget(this);
    int stackerPageNumber = ui->stackedWidgetMain->addWidget(chooserwidget);
    ui->stackedWidgetMain->setCurrentIndex(stackerPageNumber);
    connect(this, SIGNAL(settingsChangedSignal()), chooserwidget, SLOT(settingsReloadFromMainSlot()));
}
